package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ICheckInService checkInService;
    @Autowired
    private ICheckInConfigService  checkInConfigService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private IElderService elderService;
    @Autowired
    private IBedService  bedService;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }
    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //根据身份证号，判断老人是否已入住
        String idCardNo=dto.getCheckInElderDto().getIdCardNo();
        Elder oldElder =elderService.lambdaQuery()
                .eq(Elder::getIdCardNo,idCardNo)
                .one();
        //已入住，直接返回
        if(oldElder!=null&&oldElder.getStatus()==1){
            throw new BaseException("老人已入住");
        }
        //判断床位状态，更新为已占用
        long bedId =dto.getCheckInConfigDto().getBedId();
        Bed oldBed=bedService.getById(bedId);
        if(oldBed==null){
            throw new BaseException("床不存在");
        }
        oldBed.setBedStatus(1);
        bedService.updateById(oldBed);
        //新增老人信息;
        Elder elder =BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        if(oldElder!=null){
            elder.setId(oldElder.getId());
        }
        elder.setStatus(1);
        elder.setBedId(oldBed.getId());
        elder.setBedNumber(oldBed.getBedNumber());
        elderService.saveOrUpdate(elder);
        //新增签约办理
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(elder.getId().intValue());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setStatus(LocalDateTime.now().isAfter(startDate)?1:0);
        contractService.save(contract);
        //新增入住信息
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(elder.getId().longValue());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(oldBed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        checkInService.save(checkIn);
        //新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);
    }

    @Override
    public CheckInDetailVo detail(Long id) {
          CheckInDetailVo vo =new CheckInDetailVo();
          CheckIn checkIn =getById(id);
          if(checkIn==null){
              throw  new BaseException("入住信息不存在");
          }
          String json=checkIn.getRemark();
        vo.setElderFamilyVoList(JSONUtil.toList(json, ElderFamilyVo.class));
          Long elderId =checkIn.getElderId();
          Elder elder =elderService.getById(elderId);
          if(elder==null){
              throw  new BaseException("老人不存在");
          }
          Contract  contract =contractService.lambdaQuery()
                  .eq(Contract::getElderId,elder.getId())
                  .one();
          vo.setContract(contract);
          CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
          vo.setCheckInElderVo(checkInElderVo);
          CheckInConfig  checkInConfig = checkInConfigService.lambdaQuery()
                  .eq(CheckInConfig::getCheckInId,checkIn.getId())
                  .one();
        CheckInConfigVo  checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        checkInConfigVo.setStartDate(checkIn.getEndDate());
        checkInConfigVo.setEndDate(checkIn.getStartDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        vo.setCheckInConfigVo(checkInConfigVo);

          return vo;
    }

}
